<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-box">
			<view class="search-input">
				<u-icon name="search" size="30" color="#909399"></u-icon>
				<input 
					class="search-text" 
					v-model="keyword" 
					placeholder="请输入商品名称" 
					confirm-type="search"
					@confirm="onSearch"
					focus
				/>
				<u-icon v-if="keyword" name="close" size="30" color="#909399" @click="clearKeyword"></u-icon>
			</view>
			<text class="cancel-btn" @click="goBack">取消</text>
		</view>
		
		<!-- 搜索历史 -->
		<view class="history-section" v-if="!keyword && searchHistory.length > 0">
			<view class="section-header">
				<text class="section-title">搜索历史</text>
				<u-icon name="trash" size="30" color="#909399" @click="clearHistory"></u-icon>
			</view>
			<view class="history-list">
				<view 
					v-for="(item, index) in searchHistory" 
					:key="index" 
					class="history-item"
					@click="useHistoryKeyword(item)"
				>
					<text>{{item}}</text>
				</view>
			</view>
		</view>
		
		<!-- 热门搜索 -->
		<view class="hot-section" v-if="!keyword && hotKeywords.length > 0">
			<view class="section-header">
				<text class="section-title">热门搜索</text>
			</view>
			<view class="hot-list">
				<view 
					v-for="(item, index) in hotKeywords" 
					:key="index" 
					class="hot-item"
					@click="useHistoryKeyword(item)"
				>
					<text>{{item}}</text>
				</view>
			</view>
		</view>
		
		<!-- 搜索结果 -->
		<scroll-view 
			v-if="keyword && hasSearched"
			scroll-y 
			class="search-results"
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view v-if="loading && page === 1" class="loading-box">
				<u-loading mode="circle" size="36"></u-loading>
				<text class="loading-text">搜索中...</text>
			</view>
			
			<view v-else-if="productList.length === 0" class="empty-box">
				<u-empty mode="search" icon="http://cdn.uviewui.com/uview/empty/search.png"></u-empty>
				<text class="empty-text">未找到相关商品</text>
			</view>
			
			<view v-else class="product-list">
				<view 
					v-for="item in productList" 
					:key="item.id" 
					class="product-item"
					@click="goToDetail(item.id)"
				>
					<image class="product-image" :src="item.thumbnail || '/static/images/default-product.png'" mode="aspectFill"></image>
					<view class="product-info">
						<text class="product-name">{{item.name}}</text>
						<view class="product-price-box">
							<text class="product-price">¥{{item.price}}</text>
							<text v-if="item.support_points" class="product-points">{{item.points_price}}积分</text>
						</view>
						<view class="product-meta">
							<text class="product-sales">已售{{item.sales}}件</text>
							<view class="buy-btn">购买</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view v-if="loading && page > 1" class="loading-more">
				<u-loading mode="circle" size="24"></u-loading>
				<text>加载中...</text>
			</view>
			
			<view v-if="!loading && !hasMore" class="no-more">
				<text>没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyword: '', // 搜索关键词
				searchHistory: [], // 搜索历史
				hotKeywords: ['文具用品', '办公设备', '打印机', '笔记本', '钢笔', '文件夹'], // 热门搜索词
				productList: [], // 商品列表
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				hasMore: true, // 是否有更多数据
				loading: false, // 加载状态
				refreshing: false, // 下拉刷新状态
				hasSearched: false // 是否已搜索
			}
		},
		onLoad(options) {
			// 获取搜索历史
			this.getSearchHistory();
			
			// 如果有传入关键词，直接搜索
			if (options.keyword) {
				this.keyword = options.keyword;
				this.onSearch();
			}
		},
		methods: {
			// 获取搜索历史
			getSearchHistory() {
				const history = uni.getStorageSync('officeShopSearchHistory');
				if (history) {
					try {
						this.searchHistory = JSON.parse(history);
					} catch (e) {
						console.error('解析搜索历史出错', e);
						this.searchHistory = [];
					}
				}
			},
			
			// 保存搜索历史
			saveSearchHistory() {
				if (!this.keyword) return;
				
				// 将当前关键词添加到历史记录
				let history = [...this.searchHistory];
				
				// 如果已存在，先移除
				const index = history.indexOf(this.keyword);
				if (index > -1) {
					history.splice(index, 1);
				}
				
				// 添加到最前面
				history.unshift(this.keyword);
				
				// 最多保留10条记录
				if (history.length > 10) {
					history = history.slice(0, 10);
				}
				
				// 更新状态并保存
				this.searchHistory = history;
				uni.setStorageSync('officeShopSearchHistory', JSON.stringify(history));
			},
			
			// 清空搜索历史
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '确定要清空搜索历史吗？',
					success: (res) => {
						if (res.confirm) {
							this.searchHistory = [];
							uni.removeStorageSync('officeShopSearchHistory');
						}
					}
				});
			},
			
			// 使用历史关键词
			useHistoryKeyword(keyword) {
				this.keyword = keyword;
				this.onSearch();
			},
			
			// 清空关键词
			clearKeyword() {
				this.keyword = '';
				this.hasSearched = false;
			},
			
			// 执行搜索
			onSearch() {
				if (!this.keyword.trim()) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					});
					return;
				}
				
				// 保存搜索历史
				this.saveSearchHistory();
				
				// 重置分页
				this.page = 1;
				this.hasMore = true;
				this.hasSearched = true;
				
				// 加载商品列表
				this.loadProductList();
			},
			
			// 加载商品列表
			async loadProductList() {
				if (this.loading || (!this.hasMore && this.page > 1)) return;
				
				try {
					this.loading = true;
					
					// 构建请求参数
					const params = {
						page: this.page,
						pageSize: this.pageSize,
						keyword: this.keyword
					};
					
					// 发起请求
					const res = await this.$api.getOfficeProductList(params);
					
					// 处理响应数据
					if (this.page === 1) {
						this.productList = res.list || [];
					} else {
						this.productList = [...this.productList, ...(res.list || [])];
					}
					
					// 更新分页信息
					this.hasMore = (res.list || []).length === this.pageSize;
				} catch (error) {
					console.error('搜索商品失败', error);
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.refreshing = false;
				}
			},
			
			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.page++;
					this.loadProductList();
				}
			},
			
			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				this.page = 1;
				this.hasMore = true;
				this.loadProductList();
			},
			
			// 跳转到商品详情
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/officeShop/product/detail?id=${id}`
				});
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #ffffff;
}

.search-box {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.search-input {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 50rpx;
	padding: 15rpx 30rpx;
}

.search-text {
	flex: 1;
	margin: 0 10rpx;
	font-size: 28rpx;
	color: #333333;
}

.cancel-btn {
	margin-left: 20rpx;
	font-size: 28rpx;
	color: #2979ff;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
}

.section-title {
	font-size: 30rpx;
	color: #333333;
	font-weight: bold;
}

.history-list, .hot-list {
	display: flex;
	flex-wrap: wrap;
	padding: 0 20rpx 30rpx;
}

.history-item, .hot-item {
	padding: 10rpx 30rpx;
	background-color: #f5f5f5;
	border-radius: 50rpx;
	margin: 10rpx;
	font-size: 26rpx;
	color: #333333;
}

.hot-item {
	background-color: #f0f8ff;
	color: #2979ff;
}

.search-results {
	flex: 1;
	width: 100%;
}

.loading-box, .empty-box {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
}

.loading-text, .empty-text {
	margin-top: 20rpx;
	font-size: 28rpx;
	color: #909399;
}

.product-list {
	padding: 20rpx;
}

.product-item {
	display: flex;
	padding: 20rpx;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.product-image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 8rpx;
}

.product-info {
	flex: 1;
	padding-left: 20rpx;
	display: flex;
	flex-direction: column;
}

.product-name {
	font-size: 28rpx;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 15rpx;
}

.product-price-box {
	display: flex;
	align-items: baseline;
}

.product-price {
	font-size: 32rpx;
	color: #ff5500;
	font-weight: bold;
}

.product-points {
	margin-left: 10rpx;
	font-size: 24rpx;
	color: #909399;
}

.product-meta {
	margin-top: auto;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.product-sales {
	font-size: 24rpx;
	color: #909399;
}

.buy-btn {
	padding: 6rpx 20rpx;
	background-color: #2979ff;
	color: #ffffff;
	font-size: 24rpx;
	border-radius: 30rpx;
}

.loading-more, .no-more {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 30rpx 0;
	font-size: 24rpx;
	color: #909399;
}

.loading-more text {
	margin-left: 10rpx;
}
</style>
